import { Component, OnInit, OnDestroy } from '@angular/core';
import { RouterModule, Routes, Router, ActivatedRoute, ParamMap } from '@angular/router';
import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';
import { ConfirmationService, SelectItem } from 'primeng/primeng';
import { ScheduleService } from './schedule.service';
import { Schedule } from './schedule.model';
import { switchMap } from 'rxjs/operators';

@Component({
  templateUrl: './schedule-list.component.html',
  styleUrls: ['./schedule-list.component.scss'],
  providers: [ScheduleService]
})
export class ScheduleListComponent implements OnInit, OnDestroy {
  groupName: string;
  selectedItem: Schedule;
  items: Schedule[];


  cols: any[] = new Array(
    { field: 'seq', header: '序号', width: "50px" },
    { field: 'jobName', header: '任务名称', width: "200px" },
    { field: 'cronExpression', header: 'Cron表达式', width: "160px" },
    { field: 'jobStatus', header: '状态', width: "80px" },
    { field: 'interfaceName', header: '接口类', width: "" },
    { field: 'desc', header: '功能描述', width: "" }
  );

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private scheduleService: ScheduleService,
    private dialogService: MdlDialogService,
    private snackbarService: MdlSnackbarService,
    private confirmationService: ConfirmationService) {

  }

  ngOnInit() {
    this.route.paramMap.pipe(
      switchMap((params: ParamMap) => {
        this.groupName = params.get('id');
        return this.scheduleService.listScheduleByGroupName(this.groupName);
      })
    ).subscribe(data => {
      console.log(data);
      data.forEach((config, i) => config['seq'] = (i + 1));
      this.items = data;
    }, error => console.error(error));
  }

  ngOnDestroy() {
  }

  /**显示任务界面 */
  showSaveUpdateSchedule($event: MouseEvent) {
    this.router.navigate(['/schedule/detail', {
      "groupName": this.groupName,
      'jobName': this.selectedItem ? this.selectedItem.jobName : ''
    }]);
  }

  /**任务暂停 */
  pause($event) {
    this.scheduleService.pauseSchedule(this.selectedItem).subscribe(data => {
      this.scheduleService.listScheduleByGroupName(this.groupName).subscribe(data => {
        this.snackbarService.showToast('任务暂停成功');
      });
    })
  }
  /**启动暂停任务 */
  resume($event) {
    this.scheduleService.resumeSchedule(this.selectedItem).subscribe(data => {
      this.scheduleService.listScheduleByGroupName(this.groupName).subscribe(data => {
        this.snackbarService.showToast('任务重启成功');
      });
    })
  }
  /**运行一次 */
  runOnce($event) {
    this.scheduleService.runJobOne(this.selectedItem).subscribe(data => {
      this.scheduleService.listScheduleByGroupName(this.groupName).subscribe(data => {
        this.snackbarService.showToast('任务单次调度成功');
      });
    })
  }
}
